//
//  changeMailViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/6/14.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "changeMailViewController.h"

@interface changeMailViewController ()
@property (nonatomic,strong)UIButton *sureButton;
@property (nonatomic,strong)UITextField *mailField;

@end

@implementation changeMailViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = YMColor(245, 245, 245);
    self.title = @"更换邮箱";
    
    self.mailField = [[UITextField alloc]init];
    
    CGFloat y = 85;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 80)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    y += view.frame.size.height;
    
    [self addImageToView:view andImageName:@"Setting_bound mail" andTextField:self.mailField andTFstr:@"请输入邮箱"];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 1)];
    label.backgroundColor = YMColor(219, 219, 219);
    [self.view addSubview:label];
    y += 1;
    
    y += 100;
    self.sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sureButton.frame = CGRectMake(kDeviceWidth / 3.0, y, kDeviceWidth / 3.0, kDeviceWidth / 3.0 / 2.22);
    [self.sureButton setTitle:@"完  成" forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    self.sureButton.backgroundColor = YMColor(252, 160, 207);
    self.sureButton.layer.cornerRadius = 8.0;
    [self.view addSubview:self.sureButton];
    
    [self.sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];

}

-(void)addImageToView:(UIView *)view andImageName:(NSString *)imageName andTextField:(UITextField *)TF andTFstr:(NSString *)tfStr
{
    CGFloat h = view.frame.size.height;
    UIImageView *logoImage = [[UIImageView alloc]initWithFrame:CGRectMake(35, h / 4.0, h / 2.0, h / 2.0)];
    logoImage.image = [UIImage imageNamed:imageName];
    [view addSubview:logoImage];
    
    TF.frame = CGRectMake(kDeviceWidth / 4.0, 0, kDeviceWidth / 4.0 * 3, h);
    TF.placeholder = tfStr;
    [TF setValue:YMColor(201, 201, 201) forKeyPath:@"_placeholderLabel.textColor"];
    [view addSubview:TF];
}

-(void)clickSureButton
{
    if([self validateEmail:self.mailField.text])
    {
        [self postMailToServices];
    }
    else
    {
        [MBProgressHUD showError:@"邮箱格式错误!"];
    }
}


//邮箱
- (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
/**上传邮箱到服务器*/
-(void)postMailToServices
{
    NSString *urlString = @"http://120.24.178.16:8080/Health/baby/updateUserInfo.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&type=1&info=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"],[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if (data)
         {
             // 请求成功
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
             if([[dict objectForKey:@"code"] isEqualToString:@"0"])
             {
                 [MBProgressHUD showSuccess:@"更改成功"];
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [self.navigationController popToRootViewControllerAnimated:YES];
                 });
             }
             if([[dict objectForKey:@"code"] isEqualToString:@"1"])
             {
                 [MBProgressHUD showError:@"更新失败！"];
             }
             if([[dict objectForKey:@"code"] isEqualToString:@"2"])
             {
                 [MBProgressHUD showError:@"缺少参数！"];
             }
             if([[dict objectForKey:@"code"] isEqualToString:@"3"])
             {
                 [MBProgressHUD showError:@"用户不存在！"];
             }
         }
     }];
}

@end
